package cn.com.anypay.manager.common.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 手机号格式验证器实现
 */
public class PhoneNumberFormatValidator implements ConstraintValidator<PhoneNumberFormat, String> {

    private boolean allowEmpty;
    private PhoneNumberFormat.PhoneType type;
    private boolean allowCountryCode;

    // 中国大陆手机号正则表达式
    private static final String CHINA_MOBILE_PATTERN = "^1[3-9]\\d{9}$";

    // 带国家码的中国大陆手机号
    private static final String CHINA_MOBILE_WITH_CODE_PATTERN = "^(\\+86|0086)?1[3-9]\\d{9}$";

    // 中国（包含港澳台）手机号
    private static final String CHINA_ALL_PATTERN = "^(1[3-9]\\d{9}|[6-9]\\d{7}|[5-9]\\d{7})$";

    // 国际手机号（简化版）
    private static final String INTERNATIONAL_PATTERN = "^\\+?[1-9]\\d{7,14}$";

    @Override
    public void initialize(PhoneNumberFormat constraintAnnotation) {
        this.allowEmpty = constraintAnnotation.allowEmpty();
        this.type = constraintAnnotation.type();
        this.allowCountryCode = constraintAnnotation.allowCountryCode();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 空值检查
        if (value == null || value.trim().isEmpty()) {
            return allowEmpty;
        }

        // 去除空格和特殊字符
        String cleanPhone = value.replaceAll("[\\s-()]", "");

        // 根据类型选择验证规则
        return switch (type) {
            case CHINA_MOBILE -> validateChinaMobile(cleanPhone);
            case CHINA_ALL -> validateChinaAll(cleanPhone);
            case ALL -> validateInternational(cleanPhone);
        };
    }

    /**
     * 验证中国大陆手机号
     */
    private boolean validateChinaMobile(String phone) {
        if (allowCountryCode) {
            return Pattern.matches(CHINA_MOBILE_WITH_CODE_PATTERN, phone);
        } else {
            return Pattern.matches(CHINA_MOBILE_PATTERN, phone);
        }
    }

    /**
     * 验证中国（包含港澳台）手机号
     */
    private boolean validateChinaAll(String phone) {
        return Pattern.matches(CHINA_ALL_PATTERN, phone);
    }

    /**
     * 验证国际手机号
     */
    private boolean validateInternational(String phone) {
        return Pattern.matches(INTERNATIONAL_PATTERN, phone);
    }
}